package com.example.testtransition

import android.content.Context
import android.content.res.ColorStateList
import android.content.res.TypedArray
import android.graphics.*
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.annotation.DimenRes
import androidx.annotation.StyleableRes
import androidx.appcompat.content.res.AppCompatResources
import com.opensource.svgaplayer.*

/**
 * 自定义播放SVGA动画View
 */
open class CustomSVGAImageView : SVGAImageView {

    companion object {
        val DEF_STYLE_RES = R.style.Widget_MaterialComponents_CustomSVGAImageView

        private val TAG = CustomSVGAImageView::class.java.simpleName
        val SETUP_IMAGE_TYPE = 0
        val SETUP_TEXT_TYPE = 1
        val SETUP_DRAWABLE_TYPE = 2


        fun getColorStateList(
            context: Context, attributes: TypedArray, @StyleableRes index: Int
        ): ColorStateList? {
            if (attributes.hasValue(index)) {
                val resourceId = attributes.getResourceId(index, 0)
                if (resourceId != 0) {
                    val value = AppCompatResources.getColorStateList(context, resourceId)
                    if (value != null) {
                        return value
                    }
                }
            }

            // Reading a single color with getColorStateList() on API 15 and below doesn't always correctly
            // read the value. Instead we'll first try to read the color directly here.
            if (VERSION.SDK_INT <= VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                val color = attributes.getColor(index, -1)
                if (color != -1) {
                    return ColorStateList.valueOf(color)
                }
            }
            return attributes.getColorStateList(index)
        }
    }

    private var svgaParser: SVGAParser? = null
    private var mCallback: SVGAAnimationCallback? = null
    private var mClearsAfterStop = true
    private var mLoops = 1
    private var textColor = Color.WHITE
    private var textSize = resources.getDimensionPixelSize(R.dimen.mi_text_size_28) + 0f
    private var textSize_6sp = ScreenUtil.dp2px(10f).toFloat()

    constructor(context: Context) :
        super(context) {
            initShape(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet?) :
            super(context, attrs) {
        initShape(context, attrs, 0)

    }

    constructor(context: Context, attrs: AttributeSet?, defStyle : Int) :
            super(context, attrs, defStyle)  {
        initShape(context, attrs, defStyle)

    }

    fun initShape(context : Context, attrs : AttributeSet?, defStyle : Int) {
//        clearPaint = Paint()
//        clearPaint?.setAntiAlias(true)
//        clearPaint?.setColor(Color.WHITE)
//        clearPaint?.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OUT))
//        destination = RectF()
//        maskRect = RectF()
//        maskPath = Path()
//        val attributes = context.obtainStyledAttributes(attrs, R.styleable.ShapeableImageView, defStyle, CustomSVGAImageView.DEF_STYLE_RES)
//
//        strokeColor = getColorStateList(context, attributes, R.styleable.CustomSVGAImageView_strokeColor)
//
//        strokeWidth = attributes.getDimensionPixelSize(R.styleable.CustomSVGAImageView_strokeWidth, 0).toFloat()
//
//        borderPaint = Paint()
//        borderPaint?.style = Paint.Style.STROKE
//        borderPaint?.isAntiAlias = true
//        shapeAppearanceModel = ShapeAppearanceModel
//            .builder(context, attrs, defStyle, CustomSVGAImageView.DEF_STYLE_RES).build()
//        shadowDrawable = MaterialShapeDrawable(shapeAppearanceModel)
//
//        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
//            outlineProvider = OutlineProvider()
//        }
    }

    fun setmClearsAfterStop(mClearsAfterStop: Boolean) {
        this.mClearsAfterStop = mClearsAfterStop
    }

    fun setmLoops(mLoops: Int) {
        this.mLoops = mLoops
    }

    fun setTextColor(@ColorInt color: Int) {
        textColor = color
    }

    fun setTextSize(@DimenRes textRes: Int) {
        textSize = resources.getDimensionPixelSize(textRes) + 0f
    }

    /**
     * 无更换内容特效
     */
    fun showEffect(assetsName: String, callback: SVGAAnimationCallback? = null) {
        showEffect(assetsName, null, null, callback)
    }

    /**
     * 更换图片内容特效
     */
    fun showEffect(assetsName: String, dynamicImageKey: String?, dynamicImageUrl: String?, callback: SVGAAnimationCallback?) {
        showEffect(assetsName, dynamicImageKey, dynamicImageUrl, SETUP_IMAGE_TYPE, callback)
    }

    /**
     * 更换图片/文字内容特效
     */
    fun showEffect(assetsName: String, dynamicImageKey: String?, dynamicValue: String?, setupType: Int?, callback: SVGAAnimationCallback?) {
        val dynamicImageKeys = if (dynamicImageKey == null) emptyArray() else arrayOf(dynamicImageKey)
        val dynamicImageUrls = if (dynamicValue == null) emptyArray() else arrayOf(dynamicValue)
        val setupTypes = if (setupType == null) null else intArrayOf(setupType)
        showEffectTo(assetsName, dynamicImageKeys, dynamicImageUrls, setupTypes, callback)
    }

    /**
     * 更换多张图片内容特效
     */
    fun showEffectTo(assetsName: String, dynamicImageKeys: Array<String>?, dynamicImageUrls: Array<String>?, callback: SVGAAnimationCallback?) {
        showEffectTo(assetsName, dynamicImageKeys, dynamicImageUrls, false, callback)
    }

    /**
     * 更换多张图片内容特效 可以设置图片是否是圆形
     */
    fun showEffectTo(assetsName: String, dynamicImageKeys: Array<String>?, dynamicImageUrls: Array<String>?, userCircleImage: Boolean, callback: SVGAAnimationCallback?) {
        val setupTypes = if (dynamicImageKeys?.isNotEmpty() == true) IntArray(dynamicImageKeys.size) else null
        if (setupTypes?.isNotEmpty() == true) {
            for (index in 0 until setupTypes.size) {
//                Logger.i(TAG, "showEffectTo :: index = $index, value = ${setupTypes[index]}")
                setupTypes[index] = SETUP_IMAGE_TYPE
            }
        }
        showEffectTo(assetsName, dynamicImageKeys, dynamicImageUrls, userCircleImage, setupTypes, callback)
    }

    /**
     * 更换多张图片/文字内容特效
     */
    fun showEffectTo(assetsName: String, dynamicImageKeys: Array<String>?, dynamicValues: Array<String>?, setupTypes: IntArray?, callback: SVGAAnimationCallback?) {
        this.mCallback = callback
        try {
            if (svgaParser == null) {
                svgaParser = SVGAParser(context)
            }
            svgaParser!!.parse(assetsName, SVGAParseCompletion(dynamicImageKeys, dynamicValues, false, setupTypes))
        } catch (e: Exception) {
            e.printStackTrace()
            mCallback?.onError()
        }
    }

    /**
     * 更换多张图片/文字内容特效
     */
    fun showEffectTo(assetsName: String, dynamicImageKeys: Array<String>?, dynamicValues: Array<String>?, userCircleImage: Boolean, setupTypes: IntArray?, callback: SVGAAnimationCallback?) {
        this.mCallback = callback
        try {
            if (svgaParser == null) {
                svgaParser = SVGAParser(context)
            }
            svgaParser!!.parse(assetsName, SVGAParseCompletion(dynamicImageKeys, dynamicValues, userCircleImage, setupTypes))
        } catch (e: Exception) {
            e.printStackTrace()
            mCallback?.onError()
        }
    }

    /**
     * 更换图片内容特效
     */
//    fun showEffectWithPath(path: String, dynamicImageKey: String?, dynamicImageUrl: String?, callback: SVGAAnimationCallback?) {
//        val dynamicImageKeys = if (dynamicImageKey == null) emptyArray() else arrayOf(dynamicImageKey)
//        val dynamicImageUrls = if (dynamicImageUrl == null) emptyArray() else arrayOf(dynamicImageUrl)
//        showEffectWithPathTo(path, dynamicImageKeys, dynamicImageUrls, callback)
//    }

    /**
     * 更换多张图片内容特效
     */
//    fun showEffectWithPathTo(path: String, dynamicImageKeys: Array<String>?, dynamicImageUrls: Array<String>?, callback: SVGAAnimationCallback?) {
//        val setupTypes = if (dynamicImageKeys?.isNotEmpty() == true) IntArray(dynamicImageKeys.size) else null
//        if (setupTypes?.isNotEmpty() == true) {
//            for (index in 0 until setupTypes.size) {
////                Logger.i(TAG, "showEffectTo :: index = $index, value = ${setupTypes[index]}")
//                setupTypes[index] = SETUP_IMAGE_TYPE
//            }
//        }
//        showEffectWithPathTo(path, dynamicImageKeys, dynamicImageUrls, setupTypes, callback)
//    }

    /**
     * 更换多张图片/文字内容特效
     */
//    fun showEffectWithPathTo(path: String, dynamicImageKeys: Array<String>?, dynamicValues: Array<String>?, setupTypes: IntArray?, callback: SVGAAnimationCallback?) {
//        Logger.i(TAG, "showEffectWithPath :: path = $path, dynamicImageKeys = $dynamicImageKeys, dynamicValues = $dynamicValues")
//        this.mCallback = callback
//        try {
//            var filePath = path
//            val basePath = context.filesDir.absolutePath
//            if (!filePath.contains(basePath)) {
//                filePath = if (!filePath.contains("svga_res")) {
//                    "$basePath${"/svga_res/"}$path"
//                } else {
//                    "$basePath$path"
//                }
//            }
//            Logger.i(TAG, "showEffectWithPath :: filePath = $filePath")
//            val file = File(filePath)
//            if (!file.exists() || file.length() == 0L) {
//                mCallback?.onError()
//                return
//            }
//            if (svgaParser == null) {
//                svgaParser = SVGAParser(context)
//            }
//            val cacheKey = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."))
//            Logger.i(TAG, "showEffectWithPath :: cacheKey = $cacheKey")
//            svgaParser!!.parse(FileInputStream(file), cacheKey, SVGAParseCompletion(dynamicImageKeys, dynamicValues, false, setupTypes), true)
//        } catch (e: Exception) {
//            e.printStackTrace()
//            mCallback?.onError()
//        }
//    }

    /**
     * 无更换内容特效
     */
//    fun showEffect(url: URL, callback: SVGAAnimationCallback?) {
//        showEffect(url, null, null, callback)
//    }

    /**
     * 更换图片内容特效
     */
//    fun showEffect(url: URL, dynamicImageKey: String?, dynamicImageUrl: String?, callback: SVGAAnimationCallback?) {
//        showEffect(url, dynamicImageKey, dynamicImageUrl, SETUP_IMAGE_TYPE, callback)
//    }

    /**
     * 更换图片/文字内容特效
     */
//    fun showEffect(url: URL, dynamicImageKey: String?, dynamicValue: String?, setupType: Int?, callback: SVGAAnimationCallback?) {
//        val dynamicImageKeys = if (dynamicImageKey == null) emptyArray() else arrayOf(dynamicImageKey)
//        val dynamicImageUrls = if (dynamicValue == null) emptyArray() else arrayOf(dynamicValue)
//        val setupTypes = if (setupType == null) null else intArrayOf(setupType)
//        showEffectTo(url, dynamicImageKeys, dynamicImageUrls, setupTypes, callback)
//    }

    /**
     * 更换多张图片内容特效
     */
//    fun showEffectTo(url: URL, dynamicImageKeys: Array<String>?, dynamicImageUrls: Array<String>?, callback: SVGAAnimationCallback?) {
//        val setupTypes = if (dynamicImageKeys?.isNotEmpty() == true) IntArray(dynamicImageKeys.size) else null
//        if (setupTypes?.isNotEmpty() == true) {
//            for (index in 0 until setupTypes.size) {
//                Logger.i(TAG, "showEffectTo :: index = $index, value = ${setupTypes[index]}")
//                setupTypes[index] = SETUP_IMAGE_TYPE
//            }
//        }
//        showEffectTo(url, dynamicImageKeys, dynamicImageUrls, setupTypes, callback)
//    }

    /**
     * 更换多张图片/文字内容特效
     */
//    private fun showEffectTo(url: URL, dynamicImageKeys: Array<String>?, dynamicValues: Array<String>?, setupTypes: IntArray?, callback: SVGAAnimationCallback?) {
//        this.mCallback = callback
//        try {
//            if (svgaParser == null) {
//                svgaParser = SVGAParser(context)
//            }
//            svgaParser!!.parse(url, SVGAParseCompletion(dynamicImageKeys, dynamicValues, false, setupTypes))
//        } catch (e: Exception) {
//            e.printStackTrace()
//            mCallback?.onError()
//        }
//    }

    /**
     * 显示特效，可同时替换svga中的多个内容
     * 类型为文本的 ，value由2部分组成：内容+颜色值 ，2部分以逗号分割
     *
     * key -> value -> type 三者要一一对应
     */
//    fun showEffectConfigUrls(assetsName: String,
//                       dynamicImageKeys: Array<String>?,
//                       dynamicImageUrls: Array<String>?,
//                       setupTypes: IntArray?,
//                       callback: SVGAAnimationCallback?) {
//        showEffectWithPathTo(assetsName, dynamicImageKeys, dynamicImageUrls, setupTypes, callback)
//    }

    /**
     * 特效监听回调
     */
    private inner class SVGAParseCompletion(private val dynamicImageKeys: Array<String>?,
                                            private val dynamicValues: Array<String>?,
                                            private val userCircleImage: Boolean? = false,
                                            private val setupTypes: IntArray?)
        : SVGAParser.ParseCompletion {

        override fun onComplete(videoItem: SVGAVideoEntity) {
//                    ", dynamicValues = $dynamicValues, setupTypes = $setupTypes")
//
            if (!AppUtils.contextExist(context))return
            val svgaDrawable = if (dynamicImageKeys != null && dynamicValues != null && setupTypes != null
                    && dynamicImageKeys.size <= dynamicValues.size && dynamicImageKeys.size <= setupTypes.size) {
                val dynamicEntity = SVGADynamicEntity()
                for (index in dynamicImageKeys.indices) {
                    val setupType = setupTypes[index]
                    when (setupType) {
                        SETUP_IMAGE_TYPE -> {
//                            if (userCircleImage == true) {
//                                ImageDownloader.getInstance().loadCircleBitmap(context, dynamicValues[index], R.drawable.yidui_img_avatar_bg_home, object : SimpleTarget<Bitmap>() {
//                                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                                        if (resource != null) {
//                                            dynamicEntity.setDynamicImage(resource, dynamicImageKeys[index])
//                                        }
//                                    }
//                                })
//                            } else {
//                                dynamicEntity.setDynamicImage(dynamicValues[index], dynamicImageKeys[index])
//                            }
//
                        }
                        SETUP_TEXT_TYPE -> {
//                            val textPaint = TextPaint()
//                            // 字体颜色的设置，优先使用外部设置过来的。否则使用默认的。
//                            // 类型为文本的，value由2部分组成：内容+颜色值 ，2部分以逗号分割。设置的时候，会解析出来
//                            val txtAndColor = dynamicValues[index]
//                            val txtAndColorArr = txtAndColor.split(",")
//                            var txt = ""
//                            var color = ""
//                            if (txtAndColorArr?.size < 2) {
//                                textPaint.color = textColor
//                            } else {
//                                try {
//                                    txt = txtAndColorArr[0]
//                                    color = txtAndColorArr[1]
//                                    textPaint.color = Color.parseColor(color)
//                                } catch (e :Exception) {
//                                    e.stackTrace
//                                }
//                            }
//                            textPaint.textSize = textSize_6sp
//                            dynamicEntity.setDynamicText(txt, textPaint, dynamicImageKeys[index])
                        }
                        SETUP_DRAWABLE_TYPE -> {
//                            ImageDownloader.getInstance().loadToBitmap(context, DataUtils.toInt(dynamicValues[index]), object : SimpleTarget<Bitmap>() {
//                                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                                    if (resource != null) {
//                                        dynamicEntity.setDynamicImage(resource, dynamicImageKeys[index])
//                                    }
//                                }
//                            })
                        }
                    }
                }
                SVGADrawable(videoItem, dynamicEntity)
            } else {
                SVGADrawable(videoItem)
            }
            setImageDrawable(svgaDrawable)
            loops = mLoops
            clearsAfterStop = mClearsAfterStop
            startAnimation()
            mCallback?.onSuccess(this@CustomSVGAImageView)
        }

        override fun onError() {
            mCallback?.onError()
        }
    }

    /**
     * 停止特效
     */
    fun stopEffect() {
        stopAnimation(true)
    }

    interface SVGAAnimationCallback {
        fun onSuccess(view: CustomSVGAImageView)
        fun onError()
    }
}